package com.example.demo.controler;

import com.example.demo.common.AppResult;
import com.example.demo.common.ResultCode;
import com.example.demo.exception.ApplicationException;
import com.example.demo.model.User;
import com.example.demo.services.IUserService;
import com.example.demo.utils.MD5Util;
import com.example.demo.utils.StringUtil;
import com.example.demo.utils.UUIDUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

// 添加⽇志注解以便使⽤⽇志
@Slf4j
// API 描述
@Api(tags = "⽤⼾接⼝")
// 标识为了个Controller并且响应时返回Body中的数据
@RestController
// 指定路径映射
@RequestMapping("/user")

public class UserController {
    // 注⼊业务层
    @Resource
    private IUserService userService;

    // 指定接⼝URL映射
    // API 描述
    @ApiOperation("注册⽤⼾")
    @PostMapping("/register")
    public AppResult register (@ApiParam(value = "⽤⼾名") @RequestParam(value =
            "username") @NonNull String username,
                               @ApiParam(value = "昵称") @RequestParam(value =
                                       "nickname") @NonNull String nickname,
                               @ApiParam(value = "密码") @RequestParam(value =
                                       "password") @NonNull String password,
                               @ApiParam(value = "确认密码") @RequestParam(value =
                                       "passwordRepeat") @NonNull String passwordRepeat) {
        // 1.基本信息赋值
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        // 2.处理密码

        // 2.1 校验密码和确认密码是否相等
        if (!password.equals(passwordRepeat)) {
            // 记录⽇志
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常，异常信息为参数校验失败
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 2.2 加密密码
        String salt = UUIDUtil.UUID_32();
        String encryptPassword = MD5Util.md5Salt(password, salt);
        // 2.3 设置密码
        user.setPassword(encryptPassword);
        user.setSalt(salt);
        // 3. 调⽤Service
        userService.createNormalUser(user);
        // 4. 返回
        return AppResult.success();

    }


}
